package com.boyuan.huijiaoyu;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.magicsoft.app.entity.AccountInfo;
import com.magicsoft.app.helper.ToastHelper;
import com.magicsoft.app.wcf.HomeService;
import com.magicsoft.app.wcf.listener.GetMultilParamsListener;
import com.magicsoft.app.wcf.listener.PostRecordResponseListener;
import com.magicsoft.constant.Constant;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.download.BaseImageDownloader;
import com.ttcaca.cas.android.client.model.User;
import com.ttcaca.cas.android.client.utils.Helper;

public class PersonalMessageActivity extends BaseActivity implements
		OnClickListener {

	private static final int IMAGE_REQUEST_CODE = 0;
	private static final int RESULT_REQUEST_CODE = 2;
	private static final int INTENT_CHANGEMOBILE = 1;
	private static final int FILE_SELECT_CODE = 4;
	private RelativeLayout btnBack;
	private TextView txt_title;
	private User account;
	private ImageView iv_icon;// 头像
	private DisplayImageOptions options;
	private HomeService homeService;
	private AccountInfo accountInfo;
	String mobile;
	String mail;
	private String realname;
	private String address;
	private String education;
	private String sex;
	private String accountId;
	private String yonghu;
	/* 头像名称 */
	private static final String PHOTO_FILE_NAME = "temp_photo.jpg";
	private String tag = "PersonalMessageActivity";
	private String backtitle;
	private String familyname;
	private String jobname;
	private String id;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.personal_message_activity);
		Intent intent = getIntent();
		backtitle = intent.getStringExtra("backtitle");
		yonghu = intent.getStringExtra("mobile");
		SharedPreferences sp = getSharedPreferences("a.xml", 0);
		accountId = sp.getString("accountId", "");
		mobile = sp.getString("username", "");
		realname = sp.getString("realname", "");
		mail = sp.getString("mail", "");
		address = sp.getString("address", "");
		education = sp.getString("education", "");
		jobname = sp.getString("jobname", "");
		sex = sp.getString("sex", "");
		id = sp.getString("id", "");
		familyname = sp.getString("familyname", "");

		initOptions();
		prepareView();
		prepareData();
		prepareData1();
	}

	//异步加载图片
		class ImageAsyncTask extends AsyncTask<String, Void, Bitmap>{
			
			ImageView image;
			public ImageAsyncTask(ImageView image){
				this.image = image;
			}

			@Override
			protected Bitmap doInBackground(String... params) {
				Bitmap bitmap = null;
				String path = params[0];
				try {
					URL url = new URL(path);
					URLConnection openConnection = url.openConnection();
					InputStream inputStream = openConnection.getInputStream();
					bitmap = BitmapFactory.decodeStream(inputStream);
					FileOutputStream fos = new FileOutputStream(path);
					bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
				} catch (MalformedURLException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
				return bitmap;
			}
			
			@Override
			protected void onPostExecute(Bitmap result) {
				iv_icon.setImageBitmap(result);
				super.onPostExecute(result);
			}
			
		}
	
	private void prepareData1() {

//		imageLoader.clearMemoryCache();
//		imageLoader.clearDiskCache();
		String uri = Constant.photourl + id;
//		imageLoader.displayImage(uri, iv_icon, options);
		ImageAsyncTask imageAsyncTask = new ImageAsyncTask(iv_icon);
		imageAsyncTask.execute(uri);

		if (homeService == null) {
			homeService = new HomeService(PersonalMessageActivity.this);
			homeService.getPersonInfo(yonghu, new GetMultilParamsListener() {

				@Override
				public void onFinish(Object... params) {
					accountInfo = (AccountInfo) params[0];
				}

				@Override
				public void onFailed(String Message) {
					ToastHelper.showMsg(PersonalMessageActivity.this,
							"获取个人信息失败", false);
				}
			});
		}
	}

	private void initOptions() {
		options = new DisplayImageOptions.Builder()
				.showImageOnLoading(R.drawable.default_header)
				.showImageForEmptyUri(R.drawable.default_header)
				.showImageOnFail(R.drawable.default_header).cacheInMemory(true)
				.cacheOnDisc(true).considerExifParams(true)
				// .displayer(new RoundedBitmapDisplayer(20))
				.build();
	}

	private void prepareView() {
		btnBack = (RelativeLayout) findViewById(R.id.myback);
		btnBack.setOnClickListener(this);

		txt_title = (TextView) findViewById(R.id.txt_title);
		txt_title.setText("个人信息");
		
		iv_icon = (ImageView) findViewById(R.id.iv_icon);
		iv_icon.setOnClickListener(this);

		findViewById(R.id.rl_icon).setOnClickListener(this);
		//姓名
		TextView txt_realName = (TextView) findViewById(R.id.txt_personRealname);
		if("".equals(realname)){
		}else{
			txt_realName.setText(realname);
		}
		//性别
		TextView tv_personSex = (TextView) findViewById(R.id.txt_personSex);
		if("".equals(sex)){
		}else{
			tv_personSex.setText(sex);
		}
		//手机
		TextView txt_personMobile = (TextView) findViewById(R.id.txt_personMobile);
		if("".equals(mobile)){
		}else{
			txt_personMobile.setText(mobile);
		}
		//邮箱
		TextView txt_personMail = (TextView) findViewById(R.id.txt_personMail);
		if("".equals(mail)){
		}else{
			txt_personMail.setText(mail);
		}
		//地址
		TextView txt_personAddress = (TextView) findViewById(R.id.txt_personAddress);
		if("".equals(address)){
		}else{
			txt_personAddress.setText(address);
		}
		//部门
		TextView txt_personBumen = (TextView) findViewById(R.id.txt_personBumen);
		if("".equals(familyname)){
		}else{
			txt_personBumen.setText(familyname);
		}
		//职位
		TextView txt_personZhiwei = (TextView) findViewById(R.id.txt_personZhiwei);
		if("".equals(jobname)){
		}else{
			txt_personZhiwei.setText(jobname);
		}
		//学历
		TextView txt_personxueli = (TextView) findViewById(R.id.txt_personxueli);
		if("".equals(education)){
		}else{
			txt_personxueli.setText(education);
		}
		
		TextView tvback = (TextView) findViewById(R.id.tv_myback);
		tvback.setText(backtitle);

	}

	private void prepareData() {

	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.iv_icon:
			JumpDetailIcon();
			break;
		case R.id.myback:
			finish();
			break;
		case R.id.rl_icon:
			changePhoto();
			break;
		default:
			break;
		}
	}

	private void JumpDetailIcon() {
		String uri = Constant.photourl + id;
		Intent imageIntent = new Intent(PersonalMessageActivity.this,
				ImageViewZoomActivity.class);
		imageIntent.putExtra("imageurl", uri);
		startActivity(imageIntent);
	}

	private void changePhoto() {
		showFileChooser();
	}

	private void showFileChooser() {
		Intent intentFromGallery = new Intent();
		intentFromGallery.setType("image/*"); // 设置文件类型
		intentFromGallery.setAction(Intent.ACTION_GET_CONTENT);
		startActivityForResult(intentFromGallery, IMAGE_REQUEST_CODE);
	}

	@Override
	public void backClicked() {
		if (!isShowingLoading()) {
			isBackAllowed = true;

		} else {
			hideLoading();
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode,
			final Intent data) {
		if (data != null) {
			if (resultCode == Activity.RESULT_OK
					&& requestCode == IMAGE_REQUEST_CODE) {
				Uri uri = data.getData();
				startPhotoZoom(uri);
			} else if (resultCode == Activity.RESULT_OK
					&& requestCode == RESULT_REQUEST_CODE) {
				if (data != null) {
					getImageToView(data);
					//
				}
			} 
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	/**
	 * 裁剪图片方法实现
	 * 
	 * @param uri
	 */
	public void startPhotoZoom(Uri uri) {

		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		// 设置裁剪
		intent.putExtra("crop", "true");
		// aspectX aspectY 是宽高的比例
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		// outputX outputY 是裁剪图片宽高

		intent.putExtra("outputFormat", "JPEG");
		intent.putExtra("outputX", 320);
		intent.putExtra("outputY", 320);
		intent.putExtra("return-data", false);// true:不返回uri，false：返回uri
		startActivityForResult(intent, RESULT_REQUEST_CODE);
	}

	// 将裁剪的图片进行显示
	private void getImageToView(Intent data) {
		final Uri uri = data.getData();
		File file = new File(Environment.getExternalStorageDirectory(),
				PHOTO_FILE_NAME);
		Bitmap bitmap = null;
		BaseImageDownloader imageDownloader = new BaseImageDownloader(
				PersonalMessageActivity.this);
		try {
			InputStream is = imageDownloader.getStream(uri.toString(), null);
			bitmap = BitmapFactory.decodeStream(is);
			BufferedOutputStream bos = new BufferedOutputStream(
					new FileOutputStream(file));
			bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
			bos.flush();
			bos.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		//
		final Bitmap bitmap2 = bitmap;
		
		Helper.showToast(getApplicationContext(), "正在上传...");
		Helper.uploadHeadIcon(Constant.photourl, id, file,
				new PostRecordResponseListener() {
					@Override
					public void onFinish(String succString) {
						Log.e(tag, "成功");
//						imageLoader.clearMemoryCache();
//						imageLoader.clearDiskCache();
						Intent intent = new Intent();
						intent.setAction(Constant.ChangePersonHeadIcon);
						intent.putExtra("filePath", uri.toString());
						sendBroadcast(intent);
						iv_icon.setImageBitmap(bitmap2);
						ToastHelper.showMsg(PersonalMessageActivity.this, "上传"
								+ succString, false);
					}

					@Override
					public void onFailed(String failString) {
						ToastHelper.showMsg(PersonalMessageActivity.this,
								failString, false);
						Log.e(tag, "失败");
					}
				});

	}
}
